class PhraseQuiz {
    constructor() {
        this.phrases = [...phrasesData];
        this.currentQuestions = [];
        this.currentIndex = 0;
        this.score = 0;
        this.userAnswers = [];
        this.inputTimer = null;
        this.INPUT_TIMEOUT = 5000; // 5秒无输入后显示提示
        
        // 先加载数据
        this.loadReviewData();
        this.loadUserStats();
        this.loadHistory();
        
        // 再初始化界面
        this.initializeElements();
        this.bindEvents();
        
        // 最后开始新测试和检查新用户
        this.startNewQuiz();
        this.checkFirstTimeUser();
    }

    initializeElements() {
        this.contextElement = document.getElementById('context');
        this.hintElement = document.getElementById('hint');
        this.inputElement = document.getElementById('userInput');
        this.checkButton = document.getElementById('checkAnswer');
        this.showHintButton = document.getElementById('showHint');
        this.resultElement = document.getElementById('result');
        this.scoreElement = document.getElementById('currentScore');
        this.accuracyElement = document.getElementById('accuracy');
        this.newQuizButton = document.getElementById('newQuizButton');
    }

    bindEvents() {
        this.checkButton.addEventListener('click', () => this.checkAnswer());
        this.showHintButton.addEventListener('click', () => this.showHint());
        
        // 修改输入框事件监听
        this.inputElement.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.checkAnswer();
            }
            this.resetInputTimer();
        });

        // 添加键盘输入事件监听
        this.inputElement.addEventListener('input', () => {
            this.resetInputTimer();
        });

        // 当输入框获得焦点时开始计时
        this.inputElement.addEventListener('focus', () => {
            this.resetInputTimer();
        });

        // 当输入框失去焦点时清除计时器
        this.inputElement.addEventListener('blur', () => {
            if (this.inputTimer) {
                clearTimeout(this.inputTimer);
                this.inputTimer = null;
            }
        });

        this.newQuizButton.addEventListener('click', () => {
            if (confirm('确定要开始新一轮的测试吗？如果正在测试，那么当前进度将会丢失。')) {
                this.startNewQuiz();
            }
        });
    }

    resetInputTimer() {
        // 清除现有计时器
        if (this.inputTimer) {
            clearTimeout(this.inputTimer);
        }

        // 设置新的计时器
        this.inputTimer = setTimeout(() => {
            this.showHint();
        }, this.INPUT_TIMEOUT);
    }

    loadReviewData() {
        this.reviewData = JSON.parse(localStorage.getItem('reviewData') || '{}');
    }

    saveReviewData() {
        localStorage.setItem('reviewData', JSON.stringify(this.reviewData));
    }

    getReviewIntervals() {
        return [
            1 * 24 * 60 * 60 * 1000,  // 1天
            2 * 24 * 60 * 60 * 1000,  // 2天
            4 * 24 * 60 * 60 * 1000,  // 4天
            7 * 24 * 60 * 60 * 1000,  // 7天
            15 * 24 * 60 * 60 * 1000, // 15天
            30 * 24 * 60 * 60 * 1000  // 30天
        ];
    }

    updatePhraseReview(phrase, isCorrect) {
        const now = new Date().getTime();
        if (!this.reviewData[phrase.english]) {
            this.reviewData[phrase.english] = {
                stage: 0,
                nextReview: now,
                correctCount: 0,
                incorrectCount: 0
            };
        }

        const phraseData = this.reviewData[phrase.english];
        
        if (isCorrect) {
            phraseData.correctCount++;
            if (phraseData.stage < this.getReviewIntervals().length) {
                phraseData.stage++;
            }
        } else {
            phraseData.incorrectCount++;
            phraseData.stage = Math.max(0, phraseData.stage - 1);
        }

        const intervals = this.getReviewIntervals();
        phraseData.nextReview = now + intervals[phraseData.stage];
        
        this.saveReviewData();
    }

    getPhrasesToReview() {
        const now = new Date().getTime();
        return this.phrases.filter(phrase => {
            const reviewData = this.reviewData[phrase.english];
            return !reviewData || reviewData.nextReview <= now;
        });
    }

    loadUserStats() {
        this.userStats = JSON.parse(localStorage.getItem('userStats') || JSON.stringify({
            dailyAverage: 20,  // 初始每日建议数量
            lastStudyDate: null,
            consecutiveDays: 0,
            averageAccuracy: 0,
            todayStudied: 0,
            fatigueFactor: 0   // 疲劳因子，用于动态调整学习量
        }));
    }

    saveUserStats() {
        localStorage.setItem('userStats', JSON.stringify(this.userStats));
    }

    calculateRecommendedAmount() {
        const today = new Date().toDateString();
        
        // 如果是新的一天，重置今日学习量和疲劳因子
        if (this.userStats.lastStudyDate !== today) {
            this.userStats.todayStudied = 0;
            this.userStats.fatigueFactor = 0;
            this.userStats.lastStudyDate = today;
        }

        // 基础学习量：根据连续学习天数和平均正确率调整
        let baseAmount = Math.min(20, Math.max(10, 
            Math.floor(this.userStats.dailyAverage * 
            (1 + this.userStats.averageAccuracy / 100) / 2)
        ));

        // 根据疲劳因子调整
        let adjustedAmount = Math.max(5, 
            baseAmount - Math.floor(this.userStats.fatigueFactor * 2)
        );

        // 如果今天已经学习了一些，减少新的学习量
        if (this.userStats.todayStudied > 0) {
            adjustedAmount = Math.max(5, 
                Math.floor(adjustedAmount * 0.7)
            );
        }

        return adjustedAmount;
    }

    updateUserStats(accuracy) {
        const today = new Date().toDateString();
        
        // 更新统计数据
        this.userStats.averageAccuracy = 
            (this.userStats.averageAccuracy + accuracy) / 2;
        this.userStats.todayStudied += this.currentQuestions.length;
        this.userStats.fatigueFactor += 
            (100 - accuracy) / 100; // 正确率越低，疲劳因子增加越多

        // 更新连续学习天数
        if (this.userStats.lastStudyDate !== today) {
            this.userStats.consecutiveDays++;
        }
        this.userStats.lastStudyDate = today;

        // 更新每日平均学习量
        this.userStats.dailyAverage = 
            (this.userStats.dailyAverage + this.currentQuestions.length) / 2;

        this.saveUserStats();
    }

    startNewQuiz() {
        const recommendedAmount = this.calculateRecommendedAmount();
        const phrasesToReview = this.getPhrasesToReview();
        
        if (phrasesToReview.length < recommendedAmount) {
            const remainingPhrases = this.phrases.filter(
                phrase => !phrasesToReview.includes(phrase)
            );
            const additionalPhrases = this.getRandomPhrases(
                recommendedAmount - phrasesToReview.length, 
                remainingPhrases
            );
            this.currentQuestions = [...phrasesToReview, ...additionalPhrases];
        } else {
            this.currentQuestions = this.getRandomPhrases(recommendedAmount, phrasesToReview);
        }
        
        // 更新显示的总题数
        document.getElementById('totalQuestions').textContent = this.currentQuestions.length;
        
        // 启用所有控件
        this.setControlsEnabled(true);
        
        this.currentIndex = 0;
        this.score = 0;
        this.updateDisplay();
    }

    getRandomPhrases(count, sourceArray) {
        let shuffled = [...sourceArray].sort(() => 0.5 - Math.random());
        return shuffled.slice(0, count);
    }

    updateDisplay() {
        if (this.currentIndex >= this.currentQuestions.length) {
            this.finishQuiz();
            return;
        }

        const currentPhrase = this.currentQuestions[this.currentIndex];
        this.contextElement.textContent = currentPhrase.context;
        this.hintElement.textContent = '';
        this.inputElement.value = '';
        this.resultElement.textContent = '';
        this.scoreElement.textContent = this.score;
        this.accuracyElement.textContent = 
            Math.round((this.score / (this.currentIndex || 1)) * 100);

        // 重置计时器
        this.resetInputTimer();
    }

    checkAnswer() {
        // 清除提示计时器
        if (this.inputTimer) {
            clearTimeout(this.inputTimer);
            this.inputTimer = null;
        }

        const currentPhrase = this.currentQuestions[this.currentIndex];
        const userAnswer = this.inputElement.value.trim();
        const correctAnswer = currentPhrase.english;
        
        // 统一转换为小写进行比较
        const normalizedUserAnswer = this.normalizeAnswer(userAnswer);
        const normalizedCorrectAnswer = this.normalizeAnswer(correctAnswer);
        const isCorrect = normalizedUserAnswer === normalizedCorrectAnswer;

        // 保存用户原始答案
        this.userAnswers[this.currentIndex] = userAnswer;

        if (isCorrect) {
            this.score++;
            this.resultElement.textContent = 'Correct!';
            this.resultElement.style.color = 'green';
            
            setTimeout(() => {
                this.currentIndex++;
                this.updateDisplay();
            }, 1500);
        } else {
            this.resultElement.innerHTML = `
                <div style="color: red">
                    Incorrect. The answer is: ${correctAnswer}<br>
                    <span style="color: #666; font-size: 0.9em">${currentPhrase.chinese}</span>
                </div>
            `;
            
            setTimeout(() => {
                this.currentIndex++;
                this.updateDisplay();
            }, 3000);
        }

        this.updatePhraseReview(currentPhrase, isCorrect);
    }

    // 添加新方法来标准化答案
    normalizeAnswer(answer) {
        return answer
            .toLowerCase()                    // 转换为小写
            .replace(/[.,!?'"`]/g, '')       // 移除标点符号
            .replace(/\s+/g, ' ')            // 多个空格替换为单个空格
            .trim();                         // 移除首尾空格
    }

    showHint() {
        const currentPhrase = this.currentQuestions[this.currentIndex];
        
        // 如果已经显示了提示，就不要重复显示
        if (!this.hintElement.textContent) {
            this.hintElement.textContent = currentPhrase.chinese;
            
            // 添加淡入动画效果
            this.hintElement.style.opacity = '0';
            this.hintElement.style.transition = 'opacity 0.5s ease-in';
            requestAnimationFrame(() => {
                this.hintElement.style.opacity = '1';
            });
        }
    }

    finishQuiz() {
        const accuracy = Math.round((this.score / this.currentQuestions.length) * 100);
        
        // 禁用所有控件
        this.setControlsEnabled(false);
        
        this.updateUserStats(accuracy);
        this.saveResult(accuracy);
        this.displayHistory();
        
        setTimeout(() => {
            if (confirm(`Quiz finished! Your score: ${this.score}/${this.currentQuestions.length} (${accuracy}%)\nWould you like to start a new quiz?`)) {
                this.startNewQuiz();
            }
        }, 100);
    }

    saveResult(accuracy) {
        const history = JSON.parse(localStorage.getItem('quizHistory') || '[]');
        const quizDetails = this.currentQuestions.map((phrase, index) => ({
            phrase: phrase.english,
            chinese: phrase.chinese,
            context: phrase.context,
            userAnswer: this.userAnswers[index] || '',
            isCorrect: this.normalizeAnswer(this.userAnswers[index] || '') === 
                      this.normalizeAnswer(phrase.english)
        }));

        history.push({
            date: new Date().toLocaleString(),
            score: this.score,
            accuracy: accuracy,
            details: quizDetails,
            totalQuestions: this.currentQuestions.length
        });
        localStorage.setItem('quizHistory', JSON.stringify(history));
    }

    displayHistory() {
        const history = JSON.parse(localStorage.getItem('quizHistory') || '[]');
        const historyList = document.getElementById('historyList');
        
        if (!historyList) {
            console.error('History list element not found');
            return;
        }
        
        if (history.length === 0) {
            historyList.innerHTML = '<div class="history-item">暂无练习记录</div>';
            return;
        }

        historyList.innerHTML = history.reverse().map(item => `
            <div class="history-item">
                <div class="history-header">
                    <span class="history-date">${item.date}</span>
                    <span class="history-score">得分: ${item.score}/${item.totalQuestions} (${item.accuracy}%)</span>
                    <button class="toggle-details" onclick="this.parentElement.parentElement.querySelector('.history-details').classList.toggle('show')">
                        查看详情
                    </button>
                </div>
                <div class="history-details">
                    <table class="details-table">
                        <thead>
                            <tr>
                                <th>场景</th>
                                <th>正确答案</th>
                                <th>你的答案</th>
                                <th>中文</th>
                                <th>结果</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${item.details ? item.details.map(detail => `
                                <tr class="${detail.isCorrect ? 'correct' : 'incorrect'}">
                                    <td>${detail.context}</td>
                                    <td>${detail.phrase}</td>
                                    <td>${detail.userAnswer || '(未作答)'}</td>
                                    <td>${detail.chinese}</td>
                                    <td>
                                        <span class="result-icon">
                                            ${detail.isCorrect ? '✓' : '✗'}
                                        </span>
                                    </td>
                                </tr>
                            `).join('') : '<tr><td colspan="5">无详细记录</td></tr>'}
                        </tbody>
                    </table>
                </div>
                <div class="review-status">
                    下次复习: ${this.getNextReviewStatus()}
                </div>
            </div>
        `).join('');
    }

    getNextReviewStatus() {
        const phrasesToReview = this.getPhrasesToReview();
        if (phrasesToReview.length === 0) {
            return "All caught up!";
        }
        return `${phrasesToReview.length} phrases need review`;
    }

    loadHistory() {
        // 确保在 DOM 加载完成后再显示历史记录
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.displayHistory();
            });
        } else {
            this.displayHistory();
        }
    }

    checkFirstTimeUser() {
        const isFirstTime = !localStorage.getItem('hasVisited');
        if (isFirstTime) {
            this.showWelcomeGuide();
            localStorage.setItem('hasVisited', 'true');
        }
    }

    showWelcomeGuide() {
        const welcomeMessage = `
            欢迎使用英语口语短语测试系统！

            使用说明：
            1. 系统会显示英语使用场景
            2. 请在输入框中输入对应的英语短语
            3. 可以点击"Show Chinese Tip"查看中文提示
            4. 点击"Check Answer"或按回车键检查答案

            特色功能：
            • 智能调整学习量，避免疲劳
            • 根据艾宾浩斯遗忘曲线安排复习
            • 自动记录学习进度
            • 动态调整复习计划
        `;

        const guide = document.createElement('div');
        guide.className = 'welcome-guide';
        guide.innerHTML = `
            <div class="guide-content">
                <h2>新手指南</h2>
                <pre>${welcomeMessage}</pre>
                <button id="startLearning">开始</button>
            </div>
        `;

        document.body.appendChild(guide);

        document.getElementById('startLearning').addEventListener('click', () => {
            guide.remove();
            this.showTutorial();
        });
    }

    showTutorial() {
        const steps = [
            {
                element: '#context',
                message: '这里显示英语短语的使用场景，帮助你理解使用环境。'
            },
            {
                element: '#userInput',
                message: '在这里输入你认为正确的英语短语。'
            },
            {
                element: '#showHint',
                message: '如果需要提示，点击这里查看中文含义。'
            },
            {
                element: '#checkAnswer',
                message: '完成输入后，点击这里或按回车键检查答案。'
            },
            {
                element: '.stats',
                message: '这里显示你的学习进度和正确率。'
            },
            {
                element: '.history-section',
                message: '在这里查看学习历史和下次复习提醒。'
            }
        ];

        let currentStep = 0;
        const showStep = () => {
            if (currentStep >= steps.length) {
                return;
            }

            const step = steps[currentStep];
            const element = document.querySelector(step.element);
            
            // 确保元素存在
            if (!element) {
                console.error(`Element not found: ${step.element}`);
                currentStep++;
                showStep();
                return;
            }

            // 移除之前的所有提示
            document.querySelectorAll('.tutorial-tooltip').forEach(tip => tip.remove());

            // 创建新提示
            const tooltip = document.createElement('div');
            tooltip.className = 'tutorial-tooltip';
            tooltip.innerHTML = `
                <div class="tooltip-content">
                    ${step.message}
                    <button class="next-tip">${currentStep === steps.length - 1 ? '完成' : '下一步'}</button>
                </div>
            `;

            // 设置提示位置
            const rect = element.getBoundingClientRect();
            tooltip.style.position = 'fixed';
            tooltip.style.top = `${rect.bottom + 10}px`;
            tooltip.style.left = `${rect.left + (rect.width / 2)}px`;
            tooltip.style.transform = 'translateX(-50%)';

            document.body.appendChild(tooltip);

            // 高亮当前元素
            element.style.position = 'relative';
            element.style.zIndex = '1000';
            element.style.boxShadow = '0 0 0 2px #007bff';

            tooltip.querySelector('.next-tip').addEventListener('click', () => {
                // 移除高亮
                element.style.boxShadow = '';
                element.style.zIndex = '';
                
                tooltip.remove();
                currentStep++;
                showStep();
            });
        };

        showStep();
    }

    // 添加新方法来控制按钮状态
    setControlsEnabled(enabled) {
        this.checkButton.disabled = !enabled;
        this.showHintButton.disabled = !enabled;
        this.inputElement.disabled = !enabled;
        
        // 更新样式以显示禁用状态
        [this.checkButton, this.showHintButton].forEach(button => {
            if (!enabled) {
                button.classList.add('disabled');
            } else {
                button.classList.remove('disabled');
            }
        });
    }
}

// 初始化应用
let quiz;
document.addEventListener('DOMContentLoaded', () => {
    quiz = new PhraseQuiz();
}); 